package cn.e4j.modular.crm.service.impl;

import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.shiro.ShiroUser;
import cn.e4j.modular.crm.entity.EsaaT;
import cn.e4j.modular.crm.mapper.Esai100Mapper;
import cn.e4j.modular.crm.service.EsabTService;
import cn.e4j.modular.crm.service.Esai100Service;
import cn.e4j.modular.system.entity.SysMaillog;
import cn.e4j.modular.system.model.EmailProperties;
import com.baomidou.dynamic.datasource.toolkit.CryptoUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class Esai100ServiceImpl extends ServiceImpl<Esai100Mapper, EsaaT> implements Esai100Service {

    @Autowired
    private EsabTService esabTService;

    @Override
    public String getEmailById(String id) {
        return this.baseMapper.getEmailById(id);
    }

    @Override
    public Dto getSysMail() {
        return this.baseMapper.getSysEmail();
    }

    private String getTextTemplate() {
        return " 客户：%s \n 提单人员：%s \n 提单日期：%s \n " +
                "程序名称：%s \n 问题描述：%s \n";
    }

    @Override
    public EmailProperties getEmailProperties(EsaaT esaaT, String receiveType) {
        // 获取当前登录用户（客户主要联系人即默认提单人）
        ShiroUser shiroUser = ShiroKit.getUser();
        String ID = shiroUser.getID();


        Dto esab = this.getEsabData();

        // 获取收件人账号（维保服务人员和客户）
        String clientEmail = esab.getString("ESAB007"); // 客户负责人邮箱
        String ESAB025 = esab.getString("ESAB025");
        String employeeEmail = this.getEmailById(ESAB025); // 内部员工邮箱

        List<String> receiversEmail = new ArrayList<>();
        if (receiveType.equals("CLIENT")) {
            receiversEmail.add(clientEmail);
        } else if (receiveType.equals("EMPLOYEE")) {
            receiversEmail.add(employeeEmail);
        } else if (receiveType.equals("BOTH")) {
            receiversEmail.add(clientEmail);
            receiversEmail.add(employeeEmail);
        }
        // 从邮件参数获取发件人信息
        Dto senderDto = this.getSysMail();
        String smtp = senderDto.getString("MAIL_SMTP");
        String username = senderDto.getString("MAIL_EMAIL");
        String password = null;
        try {
            password = CryptoUtils.decrypt(senderDto.getString("MAIL_PAW"));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        // 构建发送邮件所需的Email_Properties
        EmailProperties properties = new EmailProperties();
        properties.setHost(smtp);
        properties.setUsername(username);
        properties.setPwd(password);
        properties.setFrom(username);
        properties.setTo(receiversEmail.toArray(new String[0]));
        properties.setSubject("客户问题提报");

        String clientName = esab.getString("ESAB030");
        properties.setText(String.format(getTextTemplate(), clientName,
                esaaT.getESAA002(), esaaT.getESAA004(), esaaT.getESAA007(), esaaT.getESAA008()));
        String ESAA009 = esaaT.getESAA009();
        if (ESAA009 != null && !ESAA009.equals("")) {
            String[] attachUrls = ESAA009.split(",");
            String[] attachNames = new String[attachUrls.length];
            for (int i = 0; i < attachUrls.length; i++) {
                // TODO　提交时修改路径地址
//                attachUrls[i] = "http://localhost:8080/smfile/" + attachUrls[i];
                attachUrls[i] = "http://180.167.0.42:9017/service/smfile/" + attachUrls[i];
                attachNames[i] = "问题截图" + (i + 1) + ".jpg";
            }

            String combinedAttachUrls = String.join(",", attachUrls);
            String combinedAttachNames = String.join(",", attachNames);
            // 本地测试用
            properties.setAttachUrl(combinedAttachUrls);
            properties.setAttachName(combinedAttachNames);
        }
        if (esaaT.getESAA012() != null) {
            String document = esaaT.getESAA012();
            String suffix = document.substring(document.lastIndexOf('.'));
            properties.setAttachName(properties.getAttachName() == null ? "" : properties.getAttachName() + ",问题文档" + suffix);
//            properties.setAttachUrl(properties.getAttachUrl()==null?"":properties.getAttachUrl() + ",http://localhost:8080/smfile/" + esaaT.getESAA012());
            properties.setAttachUrl(properties.getAttachUrl() == null ? "" : properties.getAttachUrl() + ",http://180.167.0.42:9017/service/smfile/" + esaaT.getESAA012());
        }
        return properties;
    }

    @Override
    public Dto getGwaaData(String account) {
        return this.baseMapper.getGwaaData(account);
    }

    @Override
    public Dto getEsabData() {
        ShiroUser shiroUser = ShiroKit.getUser();
        Dto gwaaDto = this.getGwaaData(shiroUser.getACCOUNT());
        Dto esabDto;
        if (gwaaDto != null) {
            esabDto = esabTService.getEsabByEsab001(gwaaDto.getString("GWAA009"));
        } else {
            esabDto = esabTService.getEsabByEsab003(shiroUser.getID());
        }
        return esabDto;
    }

    @Override
    public void addMailLog(EsaaT esaaT, String receiveType) {
        ShiroUser shiroUser = ShiroKit.getUser();
        EmailProperties properties = getEmailProperties(esaaT, receiveType);
        if (properties == null) {
            return;
        }
        String send = properties.getFrom();
        String sender = send.split("@")[0];
        SysMaillog maillog = new SysMaillog();
        maillog.setMAIL_TYPE("1");
        maillog.setMAIL_MODULE("问题管理");
        maillog.setMAIL_THEME("问题提报日志");
        maillog.setMAIL_SEND(send);
        maillog.setMAIL_SENDER(sender);
//        maillog.setMAIL_RECEIVE(properties.getTo());
        maillog.setMAIL_RECEIVER(shiroUser.getNAME());
        maillog.setMAIL_TIME(LocalDateTime.now());
        maillog.insert();
    }


}
